<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { goodsOrderForCategory, goodsOrderForProduct, orderCreateOrder } from '@/apis/apis.js'
import WxPay from '@/assets/wxpay.png'
import AliPay from '@/assets/alipay.png'
import UnionPay from '@/assets/yinlian.png'
import CashPay from '@/assets/xianjin.png'
import MemberPay from '@/assets/huiyuan.png'
import { emptyRegex } from '@/utils/utils.js'

// 数据
const paymentList = ref([
  {
    icon: WxPay,
    title: '微信',
    paymentName: 'WxPay'
  },
  {
    icon: AliPay,
    title: '支付宝',
    paymentName: 'AliPay'
  },
  {
    icon: UnionPay,
    title: '银联',
    paymentName: 'UnionPay'
  },
  {
    icon: CashPay,
    title: '现金',
    paymentName: 'CashPay'
  },
  {
    icon: MemberPay,
    title: '会员余额',
    paymentName: 'MemberPay'
  },
])
const diningPartySize = ref('')
const tableNumber = ref('')
const categoryList = ref([])
const goodsList = ref([])
const activeCategoryId = ref('')
const page = ref(1)
const total = ref(0)
const cartList = ref([])
const dialogVisible = ref(false)
const currentItem = ref({})
const currentActiveIndex = ref(0)
const paymentMethodDialogVisible = ref(false)
const paymentMethodActiveIndex = ref(0)

// 方法
const getCategoryList = async () => {
  const res = await goodsOrderForCategory()
  categoryList.value = res.data
}

const getGoodsList = async () => {
  const res = await goodsOrderForProduct({ categoryid: activeCategoryId.value, page: page.value })
  goodsList.value = res.data.res
  total.value = res.data.total
}

const addCart = (item) => {
  if (item.delist) {
    return ElMessage({ type: 'info', message: '该商品已下架', duration: 1000 })
  }
  if (item.total_stock <= 0) {
    return ElMessage({ type: 'info', message: '该商品已售罄', duration: 1000 })
  }
  if (item.hasSpecs) {
    currentItem.value = item
    currentActiveIndex.value = 0
    dialogVisible.value = true
  }
  else {
    const findResult = cartList.value.find(value => value.goods_id === item._id)
    if (findResult) {
      findResult.quantity++
      findResult.totalPrice = findResult.quantity * findResult.display_price
    }
    else {
      const obj = {
        category_id: item.category_id,
        goods_image: item.goods_image,
        goods_name: item.goods_name,
        quantity: 1,
        display_price: item.display_price,
        goods_describe: item.goods_describe,
        goods_id: item._id,
        attribute: '',
        attributeId: item.goods_stats[0]._id,
        totalPrice: 1 * item.display_price
      }
      cartList.value.push(obj)
    }
  }
}

const attrAddCart = () => {
  const findResult = cartList.value.find(value => value.attributeId === currentItem.value.goods_stats[currentActiveIndex.value]._id)
  if (findResult) {
    findResult.quantity++
    findResult.totalPrice = findResult.quantity * findResult.display_price
  }
  else {
    const obj = {
      category_id: currentItem.value.category_id,
      goods_image: currentItem.value.goods_image,
      goods_name: currentItem.value.goods_name,
      quantity: 1,
      display_price: currentItem.value.goods_stats[currentActiveIndex.value].productPrice,
      goods_describe: currentItem.value.goods_describe,
      goods_id: currentItem.value._id,
      attribute: currentItem.value.goods_stats[currentActiveIndex.value].productAttributes,
      attributeId: currentItem.value.goods_stats[currentActiveIndex.value]._id,
      totalPrice: 1 * currentItem.value.goods_stats[currentActiveIndex.value].productPrice
    }
    cartList.value.push(obj)
  }
  dialogVisible.value = false
}

const addNumber = (item) => {
  item.quantity++
  item.totalPrice = item.quantity * item.display_price
}

const minusNumber = (item) => {
  if (item.quantity <= 1) {
    cartList.value = cartList.value.filter(value => value.attributeId !== item.attributeId)
  }
  else {
    item.quantity--
    item.totalPrice = item.quantity * item.display_price
  }
}

const submit = () => {
  try {
    emptyRegex({ value: diningPartySize.value, msg: '用餐人数不能为空' })
    emptyRegex({ value: tableNumber.value, msg: '桌号不能为空' })
    if (cartList.value.length <= 0) {
      ElMessage({ type: 'info', message: '订单内容不能为空', duration: 1000 })
      throw new Error('订单内容不能为空')
    }
    paymentMethodActiveIndex.value = 0
    paymentMethodDialogVisible.value = true
  }
  catch (err) {
    console.error(err.message)
  }
}

const submitOrder = async () => {
  await orderCreateOrder({
    diningPartySize: diningPartySize.value.toString(),
    tableNumber: tableNumber.value.toString(),
    paymentMethod: paymentList.value[paymentMethodActiveIndex.value].paymentName,
    productOrder: cartList.value
  })
  ElMessage({ type: 'info', message: '下单成功', duration: 1000 })
  diningPartySize.value = ''
  tableNumber.value = ''
  cartList.value = []
  paymentMethodDialogVisible.value = false
}

// 钩子
onMounted(async () => {
  await getCategoryList()
  activeCategoryId.value = categoryList.value[0]._id
  await getGoodsList()
})

// 侦听器
watch(activeCategoryId, () => {
  page.value = 1
  getGoodsList()
})

// 计算属性
const totalPrice = computed(() => {
  return cartList.value.reduce((prev, curr) => {
    return prev + curr.totalPrice
  }, 0)
})
</script>

<template>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="input">
          <el-input type="number" placeholder="输入用餐人数" v-model.number="diningPartySize" :min="1"></el-input>
          <el-input type="number" placeholder="输入桌号" v-model.number="tableNumber" :min="1"></el-input>
        </div>
        <div class="empty" v-if="cartList.length <= 0">选择右边的商品开始点餐吧</div>
        <div class="cart">
          <el-scrollbar style="height: 604px;">
            <div class="cart-item" v-for="(item, index) in cartList" :key="index">
              <div class="left">
                <span class="item-name">{{ item.goods_name }}</span>
                <span class="item-attr" v-if="item.attribute">{{ item.attribute }}</span>
              </div>
              <div class="middle">￥{{ item.totalPrice }}</div>
              <div class="right">
                <el-button type="warning" icon="Minus" size="small" circle @click="minusNumber(item)" />
                <span class="item-number">{{ item.quantity }}</span>
                <el-button type="warning" icon="Plus" size="small" circle @click="addNumber(item)" />
              </div>
            </div>
          </el-scrollbar>
          <div class="settle">
            <span>合计：￥{{ totalPrice }}</span>
            <el-button type="warning" size="small" @click="submit">确认下单</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="category">
          <div class="category-item" v-for="item in categoryList" :key="item._id"
            :class="{ active: activeCategoryId === item._id }" @click="activeCategoryId = item._id">{{ item.categoryName
            }}</div>
        </div>
        <el-scrollbar v-if="goodsList.length > 0" style="height: 600px;">
          <div class="goods">
            <div @click="addCart(item)" style="cursor: pointer;" class="goods-item" v-for="item in goodsList"
              :key="item._id">
              <div style="position: relative;">
                <img :src="item.goods_image" class="goods-img">
                <span class="goods-tip" v-if="item.delist || item.total_stock <= 0">{{ item.delist ? '已下架' : '已售罄'
                  }}</span>
              </div>
              <span class="goods-name">{{ item.goods_name }}</span>
              <span class="goods-price">￥{{ item.display_price }}</span>
            </div>
          </div>
        </el-scrollbar>
        <div style="padding-top: 50px; height: 600px; text-align: center; color: #ccc;" v-else>无商品数据</div>
        <el-pagination :hide-on-single-page="true" :page-size="18" v-model:current-page="page" background
          layout="prev, pager, next" :total="total" style="justify-content: center; --el-color-primary: orange;"
          @current-change="getGoodsList" />
      </el-col>
    </el-row>
  </el-card>
  <el-dialog v-model="dialogVisible" title="选择规格" width="400">
    <div class="current-img">
      <el-image style="width: 100%; aspect-ratio: 2 / 1;" :src="currentItem.goods_image" fit="cover" />
    </div>
    <div class="current-name" style="margin: 15px 0; font-weight: bold;">{{ currentItem.goods_name }}</div>
    <div class="current-attr" style="display: flex; justify-content: flex-start; flex-wrap: wrap;">
      <el-button :disabled="item.productStock <= 0" style="margin-left: 0; margin-right: 12px; margin-bottom: 12px;"
        v-for="(item, index) in currentItem.goods_stats" :key="item._id"
        :type="currentActiveIndex === index ? 'success' : ''" size="small" @click="currentActiveIndex = index">{{
          item.productAttributes }}</el-button>
    </div>
    <div class="current-price" style="margin: 30px 0; font-weight: bold;">合计：￥{{
      currentItem.goods_stats[currentActiveIndex].productPrice }}</div>
    <div>
      <el-button type="success" size="default" style="width: 100%;" @click="attrAddCart">加购</el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="paymentMethodDialogVisible" title="选择支付方式" width="500">
    <div class="payment-methods">
      <div class="payment-method-item" :class="{ active: index === paymentMethodActiveIndex }"
        v-for="(item, index) in paymentList" :key="index" @click="paymentMethodActiveIndex = index">
        <img :src="item.icon">
        <span>{{ item.title }}</span>
      </div>
    </div>
    <el-button style="width: 100%;" type="warning" size="default" @click="submitOrder">确定付款</el-button>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-row {
  height: 700px;

  .el-col {
    &:first-child {
      display: flex;
      flex-direction: column;
      background-color: #f9faff;

      .input {
        display: flex;

        .el-input {
          --el-input-border-color: transparent;
          --el-input-bg-color: transparent;
          --el-input-hover-border-color: transparent;
          --el-input-focus-border-color: transparent;
        }
      }

      .empty {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #bbb;
      }

      .cart {
        flex: 1;
        display: flex;
        flex-direction: column;

        .cart-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px 10px;

          .left {
            display: flex;
            flex-direction: column;
            width: 150px;

            .item-name {
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .item-attr {
              color: #ccc;
              font-size: 14px;
            }
          }

          .right {
            display: flex;
            align-items: center;

            .item-number {
              margin: 0 20px;
            }
          }
        }

        .settle {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 10px 50px;
          background-color: #ffe7c2;

          span {
            font-weight: bold;
          }
        }
      }
    }

    &:last-child {
      .category {
        display: flex;
        flex-wrap: wrap;

        .category-item {
          margin-right: 10px;
          margin-bottom: 10px;
          padding: 5px 10px;
          background-color: #f9faff;
          font-size: 14px;
          cursor: pointer;

          &.active {
            background-color: orange;
            color: white;
          }
        }
      }

      .goods {
        display: flex;
        flex-wrap: wrap;

        .goods-item {
          display: flex;
          flex-direction: column;
          margin-right: 20px;
          margin-bottom: 20px;
          width: 12%;

          .goods-tip {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 5px 0;
            background-color: rgba($color: #000000, $alpha: 0.6);
            text-align: center;
            color: white;
          }

          .goods-img {
            width: 100%;
            aspect-ratio: 1 / 1;
            border-radius: 5px;
          }

          .goods-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}

.payment-methods {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;

  .payment-method-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 80px;
    aspect-ratio: 1/1;
    border-radius: 5px;
    cursor: pointer;

    &:hover {
      background-color: rgba($color: #ffae00, $alpha: 0.5);
    }

    &.active {
      background-color: rgba($color: #ffae00, $alpha: 0.5);
    }

    img {
      margin-bottom: 6px;
      width: 40px;
      height: 40px;
    }
  }
}
</style>
